import axios from 'axios';
import qs from 'qs';
import { Message, Loading } from 'element-ui';
import { reqTime, reqNo, getTokenId, getDesKeyFromCookie, getRSAKeyFromCookie } from './utils';
import JsEncrypt from 'jsencrypt/bin/jsencrypt';
import CryptoJS from 'crypto-js';

import router from '@/router/index';

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
// axios.defaults.headers.post['Content-Type'] = 'application/json;charset= utf-8';

// 非加密地址
// axios.defaults.baseURL = 'http://193.168.1.159:8002';

// 加密请求地址
// axios.defaults.baseURL = 'http://193.168.1.171:18002';
axios.defaults.baseURL = process.env.API_URL;
// axios.defaults.baseURL = 'https://asset.uter.com';
axios.defaults.timeout = 25000;
// console.log('process.env:', process.env);
// axios.defaults.headers.common['ABCD'] = '1234';

const keyHex = CryptoJS.enc.Utf8.parse(getDesKeyFromCookie());
let loadingInstance;
axios.interceptors.request.use(config => {
    loadingInstance = Loading.service({ fullscreen: true,text: '加载中' });
    // let basicConfig = Object.assign({}, config);
    let data = config.data;
    /**
    * 合并公共参数
    * @type {[type]}
    * 在data参数中，写法如下：
    * {
    *     "platformNo": "1",
    *     "body": {}
    * }
    */
    /**
     * 参数加密
     * @type {Object}
     */
    // 0. des加密请求参数
    let cipObj = {
        "tokenId": data.hasOwnProperty("tokenId")?data.tokenId:getTokenId(),
        "body": data.body
    };
    cipObj = JSON.stringify(cipObj);

    // let keyHex = CryptoJS.enc.Utf8.parse(getDesKeyFromCookie());
    let desEncrypted = CryptoJS.TripleDES.encrypt(cipObj, keyHex, {
        iv: CryptoJS.enc.Utf8.parse(keyHex),
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    let desEncryptedStr = desEncrypted.toString();
    let encryptParams = desEncryptedStr;
    // console.log('加密后desEncryptedStr:', desEncryptedStr);

    // 1. 对密文进行MD5摘要
    let cipMd5 = CryptoJS.MD5(desEncryptedStr);
    let cipMd5Str = cipMd5.toString();
    // console.log("密文MD5cipMd5Str:", cipMd5Str);

    // 2. 使用服务端的公钥对md5摘要进行加密,得到密文的签名（签名-sign）
    let jse = new JsEncrypt.JSEncrypt();
    jse.setPublicKey(getRSAKeyFromCookie());
    let RSAEncrypted = jse.encrypt(cipMd5Str);

    // ========参数加密 END========

    /**
     * 参数不加密
     * @type {[type]}
     */
    let noEncryptParams = {
        "tokenId": data.hasOwnProperty("tokenId")?data.tokenId:getTokenId(),
        "body": data.body
    };
    // let ciphertextEncode
    data = Object.assign({}, {
        "reqNo": reqNo(),
        "reqTime": reqTime(),
        "platformNo": data.hasOwnProperty("platformNo")?data.platformNo:"1",
        "sign": RSAEncrypted,
        "channel": "0",
        // 不加密参数
        // "ciphertext": noEncryptParams
        // 加密参数
        "ciphertext": encryptParams
    });
    config.data = data;
    // console.log(data);
    return config;
}, error => {
    loadingInstance.close();
    console.log("request error:", error);
    return Promise.reject(error);
});

axios.interceptors.response.use(
    (response) => {
        loadingInstance.close();
        if(response.data && response.data.state.code === "200"){
            /**
             * 加密传输的解密过程
             * @type {[type]}
             */
            let ciphertext = CryptoJS.TripleDES.decrypt(response.data.ciphertext, keyHex, {
                iv: CryptoJS.enc.Utf8.parse(keyHex),
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            });
            ciphertext = CryptoJS.enc.Utf8.stringify(ciphertext);
            response.data.ciphertext = ciphertext;
            // ==============解密 END ===============

            return response;
        }else{
            Message({
                message: response.data?response.data.state.message:'网络错误',
                type: 'error',
                duration: 1800
            });
            if(!response.data || response.data.state.code === "402"){
                router.push({path: '/login'});
            }
            return response;
        }
    },
    (error) => {
        loadingInstance.close();
        // console.log("error", error);
        Message({
            message: '请求失败',
            type: 'error',
            duration: 1800
        });
        return Promise.reject(error);
    }
);

export default axios;
